package flc.ast.activity;

import android.os.Bundle;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.demon.fmodsound.FmodSound;
import com.stark.audio.edit.fmod.FmodAudioPlayer;
import com.stark.audio.edit.fmod.FmodVoiceType;

import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.VoiceAdapter;
import flc.ast.bean.MyVoiceBean;
import flc.ast.databinding.ActivityVoiceChangeBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioFormat;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.WorkPathUtil;

public class VoiceChangeActivity extends BaseAc<ActivityVoiceChangeBinding> {

    public static String audioPath;
    private VoiceAdapter voiceAdapter;
    private int oldPosition = 0;
    private int selEffect = FmodVoiceType.NORMAL.getType();
    private FmodAudioPlayer mFmodAudioPlayer;
    //转换为wav文件的临时文件路径
    private String mConvertWavPath;

    @Override
    protected int onCreate() {
        return R.layout.activity_voice_change;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivVoiceChangeBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);

        mDataBinding.rvVoiceList.setLayoutManager(new GridLayoutManager(mContext, 3));
        voiceAdapter = new VoiceAdapter();
        mDataBinding.rvVoiceList.setAdapter(voiceAdapter);
        voiceAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivPlay) {//播放
            if (mFmodAudioPlayer.isPlaying()) {
                mFmodAudioPlayer.pause();
            } else {
                mFmodAudioPlayer.resume();
            }
        } else if (id == R.id.tvSave) {//保存
            save();
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        voiceAdapter.getItem(oldPosition).setSelected(false);
        voiceAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        voiceAdapter.getItem(position).setSelected(true);
        voiceAdapter.notifyItemChanged(position);
        mFmodAudioPlayer.play(mConvertWavPath);
        mFmodAudioPlayer.setAudioType(voiceAdapter.getItem(position).getType());
        selEffect = voiceAdapter.getItem(position).getType();
    }

    @Override
    protected void initData() {
        //转换格式播放
        String suffix = FileUtils.getFileExtension(audioPath);
        mDataBinding.tvAudioName.setText(FileUtils.getFileName(audioPath));
        mFmodAudioPlayer = new FmodAudioPlayer(this);
        mFmodAudioPlayer.setListener(new IAudioPlayer.IListener() {
            @Override
            public void onUpdatePlayTime(int curPlayTime, int duration) {
                mDataBinding.sbPlay.setMax((int) duration / 1000);
                mDataBinding.sbPlay.setProgress(curPlayTime / 1000);
                mDataBinding.tvPlayRight.setText(TimeUtils.millis2String(duration, "mm:ss"));
            }

            @Override
            public void onPlayChange(boolean isPlaying) {
                if (isPlaying) {
                    mDataBinding.ivPlay.setImageResource(R.drawable.aypbf);
                } else {
                    mDataBinding.ivPlay.setImageResource(R.drawable.aypzt);
                }
            }
        });
        mConvertWavPath = audioPath;
        if (!suffix.equalsIgnoreCase("wav")) {
            convert2Wav();
        }
        mFmodAudioPlayer.play(mConvertWavPath);
        //变声
        List<MyVoiceBean> listVoice = new ArrayList<>();
        listVoice.add(new MyVoiceBean(R.drawable.azc, FmodVoiceType.NORMAL.getName(), FmodVoiceType.NORMAL.getType()));
        listVoice.add(new MyVoiceBean(R.drawable.agaoxiao, FmodVoiceType.FUNNY.getName(), FmodVoiceType.FUNNY.getType()));
        listVoice.add(new MyVoiceBean(R.drawable.ads, FmodVoiceType.UNCLE.getName(), FmodVoiceType.UNCLE.getType()));
        listVoice.add(new MyVoiceBean(R.drawable.all, FmodVoiceType.LOLITA.getName(), FmodVoiceType.LOLITA.getType()));
        listVoice.add(new MyVoiceBean(R.drawable.ajqr, FmodVoiceType.ROBOT.getName(), FmodVoiceType.ROBOT.getType()));
        listVoice.add(new MyVoiceBean(R.drawable.akl, FmodVoiceType.ETHEREAL.getName(), FmodVoiceType.ETHEREAL.getType()));
        listVoice.add(new MyVoiceBean(R.drawable.ahh, FmodVoiceType.CHORUS.getName(), FmodVoiceType.CHORUS.getType()));
        listVoice.add(new MyVoiceBean(R.drawable.akb, FmodVoiceType.HORROR.getName(), FmodVoiceType.HORROR.getType()));
        voiceAdapter.setList(listVoice);
    }

    //将文件转换成wav
    private void convert2Wav() {
        String newFileName = FileUtils.getFileNameNoExtension(audioPath) + AudioFormat.WAV.getSuffix();
        String audioOutPath = WorkPathUtil.generateAudioFilePathByName(newFileName);
        EpEditor.audioFormatConvert(audioPath, audioOutPath, new OnEditorListener() {
            @Override
            public void onSuccess() {
                dismissDialog();
                mDataBinding.getRoot().post(new Runnable() {
                    @Override
                    public void run() {
                        mConvertWavPath = audioOutPath;
                    }
                });
            }

            @Override
            public void onFailure() {
                FileUtils.delete(audioOutPath);
                mConvertWavPath = null;
                ToastUtils.showShort(com.stark.common.res.R.string.convert_fail);
            }

            @Override
            public void onProgress(float progress) {
            }
        });
    }

    //变声
    private void save() {
        showDialog(getString(com.stark.common.res.R.string.saving));
        String fileName = System.currentTimeMillis() + "_" + getString(com.stark.audio.edit.R.string.ae_audio_voice_change) + ".wav";
        String audioOutPath = WorkPathUtil.generateAudioFilePathByName(fileName);
        RxUtil.create(new RxUtil.Callback<Integer>() {
            @Override
            public void doBackground(ObservableEmitter<Integer> emitter) {
                int retCode = FmodSound.INSTANCE.saveSound(mConvertWavPath, selEffect, audioOutPath);
                emitter.onNext(retCode);
            }

            @Override
            public void accept(Integer code) {
                dismissDialog();
                if (code == 0) {
                    FileP2pUtil.copyPrivateAudioToPublic(mContext, audioOutPath);
                    ToastUtils.showShort(com.stark.common.res.R.string.save_success);
                    startActivity(HomeActivity.class);
                } else {
                    ToastUtils.showShort(com.stark.common.res.R.string.save_failure);
                    FileUtils.delete(audioOutPath);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mFmodAudioPlayer != null) {
            mFmodAudioPlayer.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mFmodAudioPlayer != null) {
            mFmodAudioPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mFmodAudioPlayer != null) {
            mFmodAudioPlayer.stop();
        }
    }

}